<?php
/**
 * Created by PhpStorm.
 * User: gabriel
 * Date: 18-11-12
 * Time: 下午6:07
 * CURL
 */
namespace Common;

class CURL {
  public function get(string $url, array $headers=[]):string {
    $curl = curl_init($url);
    //设置超时
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);

    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    if (count($headers) != 0) {
      curl_setopt($curl, CURLOPT_URL, $url.'?'.http_build_query($headers));
    }

    $res = curl_exec($curl);

    if ($res === false || curl_errno($curl)) {
      Logger::getInstance()->info("curl get error! url is $url, and errcode is ".curl_error($curl));
      return "";
    }

    curl_close($curl);
    return $res;
  }

  public function post(string $url, string $data, array $headers
    , string $certFileName='', string $keyFileName=''):string {
    $curl = curl_init($url);

    //设置超时
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);

    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    if (count($headers) != 0) {
      curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }

    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

    if ($certFileName != '' && $keyFileName != '') {
      curl_setopt($curl, CURLOPT_SSLCERTTYPE, 'PEM');
      curl_setopt($curl, CURLOPT_SSLCERT, $certFileName);
      curl_setopt($curl, CURLOPT_SSLKEYTYPE, 'PEM');
      curl_setopt($curl, CURLOPT_SSLKEY, $keyFileName);
    }

    $res = curl_exec($curl);

    if ($res === false || curl_errno($curl)) {
      Logger::getInstance()->info("curl post error! url is $url, and errcode is "
        .curl_error($curl));
      return "";
    }

    curl_close($curl);
    return $res;
  }

}